package com.example.simpletask

import android.content.Context
import android.content.Intent
import android.os.Bundle
import android.view.LayoutInflater
import androidx.appcompat.app.AppCompatActivity
import androidx.lifecycle.ViewModelProvider
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.google.android.material.floatingactionbutton.FloatingActionButton

/**
 * 主界面，显示任务列表就是在这
 */
class MainActivity : AppCompatActivity() {

    companion object {
        /**
         * 方便别的页面跳转的函数
         */
        fun start(context: Context) {
            val intent = Intent(context, MainActivity::class.java)
            context.startActivity(intent)
        }
    }

    lateinit var missionList: ArrayList<Mission>
    lateinit var adapter: MissionAdapter
    lateinit var dbHelper: DbHelper

//    OnCreate函数会在每次加载这个页面时都执行
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

//        初始化数据库，并页面创建时将任务都加载到列表中
        dbHelper = DbHelper(this)
        missionList = dbHelper.loadAllMissions()

        /**
         * 通过recyclerView将任务组装成卡片渲染到屏幕上
         * 任务卡片的交互代码在MissionAdapter中
         */
        val layoutManager = LinearLayoutManager(this)
        val recyclerView = findViewById<RecyclerView>(R.id.recyclerView)
        recyclerView.layoutManager = layoutManager
        adapter = MissionAdapter(this, missionList, dbHelper)
        recyclerView.adapter = adapter

//        悬浮按钮，点击进入添加菜单(AddActivity)
        val fab: FloatingActionButton = findViewById(R.id.fab)
        fab.setOnClickListener{
            val intent = Intent(this, AddActivity::class.java)
            startActivity(intent)
        }
    }
}